# app/db_operations.py
import pymysql
import sys


class Database:
    def __init__(self, host='localhost', port=3306, user='root', password='lang520520', database='movieFriends',
                 charset='utf8'):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    def connect(self):
        return pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset
        )

    def execute(self, sql, params=None):
        conn = self.connect()
        cur = conn.cursor()
        try:
            if params:
                cur.execute(sql, params)
            else:
                cur.execute(sql)
            conn.commit()
            result = cur.fetchall()
            cur.close()
            conn.close()
            return result
        except pymysql.err.OperationalError as e:
            cur.close()
            conn.close()
            sys.exit()
